package com.sojoys.artifact.plugin.netty.coder;

import java.util.List;

import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.manager.MessageManager;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class NettyMessageDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		if (in.readableBytes() < 10) {
			return;
		}
		IMessage msg = MessageManager.me().create();
		msg.setLength(in.readIntLE());
		msg.setCommandId(in.readShortLE());
		msg.setStatus(in.readIntLE());
		int bodyLength = msg.getLength() - 10 + 4;
		byte[] body = new byte[bodyLength];
		in.readBytes(body);
		msg.setBody(body);
		out.add(msg);
	}
}
